from csv import writer
from tkinter import Tk, filedialog
import requests
from bs4 import BeautifulSoup
Tk().withdraw()

region_pinyin_list = ["chaoyang", "haidian", "fengtai", "xicheng", "dongcheng",
               "changping","daxing","tongzhou", "fangshan","shunyi","shijingshan",
               "miyun","mentougou","huairou","yanqing","pinggu"]

region_list = ["朝阳","海淀","丰台","西城","东城","昌平","大兴","通州","房山","顺义",
               "石景山","密云","门头沟","怀柔", "延庆", "平谷", "燕郊"]

region_dict= dict(zip(region_pinyin_list, region_list))

for region in region_pinyin_list:
    urls = [f"https://newhouse.fang.com/house/s/{region}/b91/",
            f"https://newhouse.fang.com/house/s/{region}/b92/",
            f"https://newhouse.fang.com/house/s/{region}/b93/",
            f"https://newhouse.fang.com/house/s/{region}/b94/"]
    
    COLUMN_HEADERS = ("房子名称","布局","面积","地址","电话","信息","价格")
    ROWS = []

    for url in urls:
        
        response = requests.get(url)

        # 使用 BeautifulSoup 解析页面内容
        soup = BeautifulSoup(response.text, 'html.parser')

        # 提取房子的详细信息
        house_details = soup.find_all('div', class_='nlc_details')

        for house in house_details:
            # 获取房子名称
            house_name = house.find('div', class_='nlcd_name')
            if house_name:
                house_name_value = house_name.get_text(strip=True)
                print("房子名称:", house_name_value)
            else:
                hosue_name = " "

            # 获取布局和面积
            house_type = house.find('div', class_='house_type')
            if house_type:
                house_type_value = house_type.get_text(strip=True)
                house_layout = house_type_value.split("—")[0]
                house_area = house_type_value.split("—")[-1]            
                print("布局和面积:", house_type_value)
            else:
                house_type_value = " "

            # 获取地址
            address = house.find('div', class_='address')
            if address:
                address_value = address.get_text(strip=True)
                print("地址:", address_value)
            else:
                address_value = " "

            # 获取电话
            phone = house.find('div', class_='tel')
            if phone:
                phone_value = phone.get_text(strip=True)
                print("电话:", phone_value)
            else:
                phone_value = " "

            # 获取 Tag 信息
            tags = house.find('div', class_='fangyuan')
            if tags:
                tages_value = tags.get_text(strip=True)
                print("Tag:", tages_value)
            else:
                tages_value = " "

            # 获取单价和总价
            price = house.find('div', class_='price_fix')
            if price:
                unit_price = price.find('div', class_='nhouse_price')
                total_price = price.find('p', class_='zj_price')
                if unit_price:
                    unit_price_value = unit_price.get_text(strip=True)
                    print("单价:", unit_price_value)
                if total_price:
                    total_price_value = total_price.get_text(strip=True)
                    print("总价:", total_price_value)
                
                price_value = unit_price_value + " " + total_price_value
                    
            row = (house_name_value,house_layout,house_area,address_value,phone_value,tages_value,price_value)
            ROWS.append(row)

    MY_FILE = filedialog.asksaveasfilename(title="Save as...",
                                        filetypes=(("Comma Separated Values", "*.csv"),),
                                        initialfile=f"{region_dict.get(region)}.csv")#这一行的意思是首选文件名

    with open(MY_FILE, "w", encoding="utf-8-sig", newline="")as csv_file:
        csv_writer = writer(csv_file)
        csv_writer.writerow(COLUMN_HEADERS)
        csv_writer.writerows(ROWS)


    
    

